//
//  ARPostEditViewModel.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/11.
//

import Foundation

class ARPostEditViewModel {

    static let maxImageCount = 4
    
    /// 图片
    private var _imageArray: [String] = []
    var imageArray: [String] { _imageArray }
    
    /// 外部更新
    var titleStr: String?
    var contentStr: String?
    
    // MARK: - Action
    
    func numberOfItem() -> Int {
        if imageArray.count >= Self.maxImageCount {
            return imageArray.count
        }
        return imageArray.count + 1
    }
    
    func isTakePhotoOf(item: Int) -> Bool {
        if imageArray.count >= Self.maxImageCount {
            return false
        }
        
        // 判断是否最后一个
        return item > (imageArray.count - 1)
    }
    
    func pathOf(item: Int) -> String? {
        if item >= _imageArray.count {
            return nil
        }
        return _imageArray[item]
    }
    
    func deleteImageOf(_ path: String) {
        _imageArray.removeAll { p in
            return path == p
        }
    }
    
    func addImage(_ path: String) {
        _imageArray.append(path)
    }
    
    // MARK: -
    
    /// 判断是否可以发布作品
    func judgeWorkCanPost() -> Bool {
        return _imageArray.isEmpty == false && (contentStr?.isEmpty ?? true) == false && (titleStr?.isEmpty ?? true) == false
    }
    
    func createWork() -> ARWorkModel? {
        if self.judgeWorkCanPost() == false {
            return nil
        }
        
        // 填充内容
        let work = ARWorkModel()
        // 填充数据
        work.author = ARUserManager.shared.userModel
        work.authorId = ARUserManager.shared.userId
        work.workTitle = self.titleStr!
        work.workDescription = self.contentStr!
        work.localCoverPath = _imageArray.first
        work.localPicPaths = _imageArray
        
        work.id = "\(work.authorId ?? "Unknown")_\(Date().timeIntervalSince1970)"
        
        return work
    }
}
